<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑患者' : '新建患者'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入患者姓名"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="formData.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="formData.birthDate"
              type="date"
              placeholder="请选择出生日期"
              style="width: 100%"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄">
            <el-input v-model="calculatedAge" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号码"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="formData.idCard"
              placeholder="请输入身份证号"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              type="email"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职业" prop="occupation">
            <el-input
              v-model="formData.occupation"
              placeholder="请输入职业"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="formData.address"
          placeholder="请输入详细地址"
          clearable
        />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="紧急联系人" prop="emergencyContact">
            <el-input
              v-model="formData.emergencyContact"
              placeholder="请输入紧急联系人姓名"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="紧急联系电话" prop="emergencyPhone">
            <el-input
              v-model="formData.emergencyPhone"
              placeholder="请输入紧急联系电话"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="婚姻状况" prop="maritalStatus">
            <el-select
              v-model="formData.maritalStatus"
              placeholder="请选择婚姻状况"
              style="width: 100%"
            >
              <el-option label="未婚" value="single" />
              <el-option label="已婚" value="married" />
              <el-option label="离异" value="divorced" />
              <el-option label="丧偶" value="widowed" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="血型" prop="bloodType">
            <el-select
              v-model="formData.bloodType"
              placeholder="请选择血型"
              style="width: 100%"
            >
              <el-option label="A型" value="A" />
              <el-option label="B型" value="B" />
              <el-option label="AB型" value="AB" />
              <el-option label="O型" value="O" />
              <el-option label="未知" value="unknown" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="过敏史">
        <el-input
          v-model="formData.allergies"
          type="textarea"
          :rows="2"
          placeholder="请输入过敏史，如无请填写'无'"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="既往病史">
        <el-input
          v-model="formData.medicalHistory"
          type="textarea"
          :rows="2"
          placeholder="请输入既往病史，如无请填写'无'"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="家族病史">
        <el-input
          v-model="formData.familyHistory"
          type="textarea"
          :rows="2"
          placeholder="请输入家族病史，如无请填写'无'"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  patient: {
    type: Object,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const formRef = ref()
const loading = ref(false)

const formData = reactive({
  name: '',
  gender: '',
  birthDate: '',
  phone: '',
  idCard: '',
  email: '',
  occupation: '',
  address: '',
  emergencyContact: '',
  emergencyPhone: '',
  maritalStatus: '',
  bloodType: '',
  allergies: '',
  medicalHistory: '',
  familyHistory: '',
  remark: ''
})

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const calculatedAge = computed(() => {
  if (!formData.birthDate) return ''
  const today = new Date()
  const birthDate = new Date(formData.birthDate)
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  return age >= 0 ? `${age}岁` : ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { 
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, 
      message: '请输入正确的身份证号', 
      trigger: 'blur' 
    }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  emergencyContact: [
    { required: true, message: '请输入紧急联系人', trigger: 'blur' }
  ],
  emergencyPhone: [
    { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 方法
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

const resetForm = () => {
  Object.assign(formData, {
    name: '',
    gender: '',
    birthDate: '',
    phone: '',
    idCard: '',
    email: '',
    occupation: '',
    address: '',
    emergencyContact: '',
    emergencyPhone: '',
    maritalStatus: '',
    bloodType: '',
    allergies: '',
    medicalHistory: '',
    familyHistory: '',
    remark: ''
  })
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const fillForm = (patient) => {
  if (patient) {
    Object.assign(formData, {
      name: patient.name || '',
      gender: patient.gender || '',
      birthDate: patient.birthDate || '',
      phone: patient.phone || '',
      idCard: patient.idCard || '',
      email: patient.email || '',
      occupation: patient.occupation || '',
      address: patient.address || '',
      emergencyContact: patient.emergencyContact || '',
      emergencyPhone: patient.emergencyPhone || '',
      maritalStatus: patient.maritalStatus || '',
      bloodType: patient.bloodType || '',
      allergies: patient.allergies || '',
      medicalHistory: patient.medicalHistory || '',
      familyHistory: patient.familyHistory || '',
      remark: patient.remark || ''
    })
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const submitData = { ...formData }
    
    // 计算年龄
    if (submitData.birthDate) {
      const today = new Date()
      const birthDate = new Date(submitData.birthDate)
      let age = today.getFullYear() - birthDate.getFullYear()
      const monthDiff = today.getMonth() - birthDate.getMonth()
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--
      }
      submitData.age = age
    }
    
    emit('submit', submitData)
  } catch (error) {
    ElMessage.error('请检查表单输入')
  } finally {
    loading.value = false
  }
}

// 监听器
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.isEdit && props.patient) {
        fillForm(props.patient)
      } else {
        resetForm()
      }
    }
  },
  { immediate: true }
)

watch(
  () => props.patient,
  (newPatient) => {
    if (props.visible && props.isEdit && newPatient) {
      fillForm(newPatient)
    }
  },
  { deep: true }
)
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px 20px 0 20px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 60px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  :deep(.el-dialog__body) {
    padding: 15px 15px 0 15px;
  }
  
  :deep(.el-form) {
    label-width: 80px !important;
  }
  
  :deep(.el-col) {
    width: 100% !important;
    margin-bottom: 10px;
  }
}

@media (max-width: 480px) {
  :deep(.el-dialog) {
    width: 100% !important;
    margin: 0;
    height: 100vh;
    border-radius: 0;
  }
  
  :deep(.el-dialog__header) {
    padding: 15px 20px;
  }
  
  :deep(.el-dialog__body) {
    padding: 10px 20px 0 20px;
    height: calc(100vh - 120px);
    overflow-y: auto;
  }
  
  :deep(.el-dialog__footer) {
    padding: 15px 20px;
  }
}
</style>